<template>
  <div>
    <div class="query-history" v-if="showPage" v-loading="loadingInstance" element-loading-text="数据加载中">
      <iframe v-if="isNeed" style="width: 100%;height: 500px;border: 0" :src="ztsxUrl"></iframe>
      <template v-else>
        <!--拉取中-->
        <div v-if="asyncTaskStatu=='0'">

          <div class="main-content" style="width: 300px">
            <p v-if="ztTitle=='任务平台数据未同步请前往完成全部信息同步'" class="qh-item qh-item1">
              {{ztTitle}}
            </p>
            <p v-else-if="ztTitle=='若信息已完成同步，请点击下方[已完成同步]按钮'" class="qh-item qh-item2">
              若信息已完成同步，请点击下方<br/>[已完成同步]按钮
            </p>


            <div v-if="ztTitle=='任务平台数据未同步请前往完成全部信息同步'" class="item qh-item_top qh-item_top1">
              <span>数据需全部同步完成才能下载成功，同步完成</span><br/>
              <span>后返回当前页耐心等待</span><br/>
              <el-button type="primary" size="mini" @click="showSqsDialog" style="width: 170px;margin: 50px 0">点击此处前往同步数据</el-button>
            </div>
            <div v-else-if="ztTitle=='若信息已完成同步，请点击下方[已完成同步]按钮'">
              <p style="text-align: center">
                <img style="height: 140px" src="../../assets/homeNew/querying.gif" />
              </p>
              <p style="text-align: center; color: #FFA113; font-weight: bold;">
                数据下载中，大约需要1~3分钟
              </p>
              <!--            <p style="text-align: center; font-weight: bold; margin-top: 40px;">
                            数据内容
                          </p>
                          <div v-for="(item,index) in result" class="item qh-item_top">
                            <span style="font-weight: bold; font-size: 13px;">{{ item }}</span>
                            <span class="qi-title" v-if="index<4">
                               <i style="color: #40E073;font-size: 24px" class="el-icon-success"></i>
                            </span>
                            <span style="padding-right: 5px;" v-else class="qi-title">...</span>
                          </div>-->
            </div>
          </div>
        </div>

        <!--拉取失败-->
        <div v-else-if="asyncTaskStatu=='-1'||asyncTaskStatu=='2'">
          <p class="qh-item" style="margin: 50px 0">
            <img src="../../assets/tszs/rz-fail.png" alt="">
          </p>
          <p class="qh-item qh-item_font" style="margin-top: 0">
            数据传输失败
          </p>
          <p class="qh-item qh-item_norm">
            抱歉！{{asyncTaskStatu=='-1'?'您需要重新拉取数据':'您的企业不属于退税企业'}}，如有疑问，请联系<span class="kf-item">客服{{kfPhone}}</span>
          </p>
          <p class="qh-item">
            <el-button @click="tryQueryAgain" :disabled="showBtn" type="warning" style="width: 120px" class="base-btn apply-btn">
              重新拉取
            </el-button>
          </p>
        </div>

        <!--拉取成功-->
        <div v-else-if="asyncTaskStatu=='1'">
          <div class="qh-success">
            <i class="el-icon-circle-check"></i>
          </div>
          <div class="qh-success_title">
            数据传输成功
          </div>
          <div style="text-align: center;color: #C7C7C7">
            点击完成按钮，继续申请贷款
          </div>
          <p style="text-align: center">
            <el-button @click="finishedQuery" type="warning" style="width: 120px" class="base-btn apply-btn">
              完成
            </el-button>
          </p>
        </div>

        <!--连连通异常逻辑-->
        <div v-else-if="asyncTaskStatu=='9999'">
          <div class="qh-success">
            <i class="el-icon-circle-close"></i>
          </div>
          <div class="qh-success_title">
            系统异常
          </div>
          <div style="text-align: center;color: #C7C7C7">
            点击重试按钮，重新拉取数据！
          </div>
          <p style="text-align: center">
            <el-button @click="tryQueryAgain" :disabled="showBtn" type="warning" style="width: 120px" class="base-btn apply-btn">
              重试
            </el-button>
          </p>
        </div>
      </template>
    </div>
    <e-sign :formObject="formObject" ref="eSign" :showEsign="showEsign" @closeSign="closeSign" @goSign="goSign"></e-sign>
  </div>
</template>

<script>
import {mapState} from 'vuex';
import {queryToken} from '../../api/login/login';
import {getSyncTask,isHistoricalTaxRebate} from '@/api/tszs/tszs';
import eSign from "../common/esign/index.vue";
import {isESign} from '@/api/authen/agreed';
import {queryUserKyc} from "../../api/plat/plat";

export default {
  name: "queryHistory",
  components: {eSign},
  data() {
    return {
      showEsign: false,
      checkXY: false,
      showBtn: false,
      btnFinishTitle:'已完成同步',
      btnFinish: false,
      ztTitle: '任务平台数据未同步请前往完成全部信息同步',
      asyncTaskStatu: null,
      title: '',
      result: ['企业基础数据','历史退税数据','纳税申报表','利润表','资产负债表'],
      myTimer: null,
      isNeed:true,
      ztsxUrl:'',
      showPage:false,
      kfPhone:process.env.LLT_KF_PHONE,
      loadingInstance:true,
      formObject:{
        businessLicenseUrl: '',
        certificateExpirationDate: '',
        certificateRegistrationDate: '',
        contactsIdentificationCard: '',
        contactsIdentificationName: '',
        contactsIdentificationNumber: '',
        corporationStep: 'step6',
        identificationNumber: '',
        legalPerson: '',
        photoBackUrl: '',
        photoFrontUrl: '',
        tenantName: '',
        uscCode: '',
        corporatePhone:'',
        photoVerifyCode:'',
        contactsIdentificationVerifyCode:'',
        isProperty:''
      }
    }
  },
  props: ['busType'],
  computed: mapState({
    user(state) {
      return state.user;
    }
  }),
  destroyed() {
    !!this.myTimer && clearInterval(this.myTimer);
    window.removeEventListener('message',this.handler,false);
  },
  mounted(){
    let uscCode = this.user.user.uscCode?this.user.user.uscCode:'';
    this.initPage();
    this.isNeedSign(uscCode);
  },
  methods: {
    goSign() {
      let uscCode = this.user.user.uscCode?this.user.user.uscCode:'';
      this.isNeedSign(uscCode,()=>{
        if (this.checkXY) {
          this.showEsign = false;
          this.submitSqs();
        } else {
          this.$refs['eSign'].setParam();
          this.showEsign = true;
        }
      });
    },
    /***
     * 是否需要进行签章(签章是否过期)
     * false未签章
     * true 已签章
     */
    isNeedSign(uscCode, callback){
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      isESign(uscCode).then(res=>{
        loading.close();
        if(res.code==200){
          this.checkXY = res.data;
          callback && callback()
        }
      });
    },
    closeSign() {
      this.showEsign = false;
    },
    showSqsDialog(){
      if (this.checkXY) {
        this.submitSqs();
      } else {
        let uscCode = this.user.user.uscCode?this.user.user.uscCode:'';
        queryUserKyc(uscCode).then(res=>{
          if(res.code==200) {
            for (let key in this.formObject) {
              if (key == 'isProperty') {
                this.formObject[key] = Number(res.data[key]);
              } else {
                this.formObject[key] = res.data[key];
              }
            }
            this.showEsign = true;
          }
        });
      }
    },
    initPage(){
      let _ = this;
      let uscCode = this.user.user.uscCode?this.user.user.uscCode:'';
      queryToken().then(res=> {
        if (res.code == 200) {
          _.loadingInstance = false;
          _.ztsxUrl = process.env.ZT_SCSX + '?token='+res.data+'&nsrsbh=' + uscCode;//测试用账号 '9133010871548570XB'
        }
      }).catch(e=>{
        _.loadingInstance = false;
      })
      this.setPageTitle();
      //先清除监听
      window.removeEventListener('message',this.handler,false);

      this.initQueryHistory();
    },

    async submitSqs(){
      this.ztTitle = '若信息已完成同步，请点击下方[已完成同步]按钮';
      setTimeout(() => { window.open(process.env.ZT_DATA, '_blank'); }, 100);
    },
    /***
     *中天通知
     *
     */
    handler(event) {
      if(event.data.status==='ok'){
        this.isNeed = false;
        this.queryTasks()
      }
    },
    /***
     *页面初始化
     *设置title
     */
    setPageTitle() {
      if (this.busType == 'Apply') {
        this.title = '我们将拉取数据并上传连连通用于授信';
      } else if (this.busType == 'Refresh') {
        this.title = '我们将拉取数据并上传连连通用于贷款申请';
      } else if (this.busType == 'Drawdown') {
        this.title = '我们将拉取数据并上传连连通用于支用';
      }
    },
    /***
     *完成拉取数据操作
     *
     */
    finishedQuery(){
      if (this.busType == 'Apply') {
        this.$emit('history-completed');
      } else if (this.busType == 'Refresh') {
        this.$router.push({path: '/plat'});
      }
    },
    /***
     * 是否存在1个月内拉取的历史退税数据
     * 1 有， -1 无
     */
    initQueryHistory(param) {
      let _ = this;
      let uscCode = this.user.user.uscCode?this.user.user.uscCode:'';
      this.showPage = false;
      isHistoricalTaxRebate(uscCode).then(res=>{
        if(res.code==200){
          if(res.data=='1'){
            _.$emit('history-completed');
          }else if(res.data=='-1'){
            _.showPage = true;
            if(param === 'again'){
              _.isNeed = false;
              _.queryTasks();
            }else{
              //监听响应事件
              window.addEventListener('message',_.handler,false);
            }
          }
        }
      }).catch(e=>{
        _.errorHandler();
      })
    },
    /***
     *定时轮询任务
     *每隔10s
     */
    queryTasks(){
      let _ = this;
      this.showEsign = false;
      this.intervalAxios();
      this.myTimer = setInterval(()=> {
        _.intervalAxios();
      }, 10000);
    },
    /***
     *查询同步任务结果
     *1成功，0拉取中 -1拉取失败
     */
    intervalAxios(){
      let _ = this;
      let uscCode = this.user.user.uscCode?this.user.user.uscCode:'';
      getSyncTask(uscCode).then(res => {
        if (res.code == 200) {
          _.asyncTaskStatu = res.data;
          //定时任务结果
          if(_.asyncTaskStatu=='1'){
            !!_.myTimer && clearInterval(_.myTimer);
          }else if(_.asyncTaskStatu=='0'){
            console.log('数据拉取中！');
          }else if(_.asyncTaskStatu=='-1'||_.asyncTaskStatu=='2'){
            !!_.myTimer && clearInterval(_.myTimer);
          }
        }
      }).catch(e => {
        _.errorHandler();
      })
    },
    /***
     *接口异常处理
     *
     */
    errorHandler(){
      this.isNeed = false;
      this.showPage = true;
      this.asyncTaskStatu = '9999';
    },
    /***
     *重新发起操作
     *
     */
    tryQueryAgain(){
      !!this.myTimer && clearInterval(this.myTimer);
      this.myTimer = null;

      if (!this.showBtn) {
        this.showBtn = true;
        this.ztTitle = '任务平台数据未同步请前往完成全部信息同步';
        this.initQueryHistory('again');
        setTimeout(() => {
          this.showBtn = false;
        }, 4000);
      }

    }
  }
}
</script>

<style lang="scss">
.query-history {
  text-align: center;
  width: 100%;
  float: left;
  background: white;
  min-height: 300px;

  .qh-success{
    text-align: center;
    margin-top: 100px;
    margin-bottom: 8px;
    .el-icon-circle-check{
      font-size: 48px;
      color: #0fbc0a;
    }
    .el-icon-circle-close{
      font-size: 48px;
      color: #ff0000;
    }
  }
  .qh-success_title{
    text-align: center;
    font-weight: bold;
    margin-bottom: 8px
  }

  .main-top {
    font-weight: bold;
    text-align: center;
    float: left;
    width: 100%;
    margin: 28px 0;
  }

  .last-btn {
    margin-top: 50px;
    margin-bottom: 100px;
  }

  .error {
    width: 100%;
    float: left;
    margin-top: 60px;
    text-align: center;

    .top-title {
      font-weight: bold;
      margin: 20px 0;
      width: 100%;
      float: left;
    }

    .middle-title {
      font-weight: normal;
      font-size: 14px;
      width: 100%;
      float: left;

      .phone {
        color: #FFA01D;
      }
    }
  }

  .qh-item {
    text-align: center;
    width: 100%;
    float: left;
    font-size: 18px;
  }
  .qh-item1 {
    font-weight: bold;
    text-align: left;
    margin-top: 60px
  }
  .qh-item2{
    font-weight: bold;
    text-align: left;
    visibility: hidden
  }

  .qh-item_font {
    font-weight: bold;
    font-size: 16px;
  }

  .qh-item_norm {
    font-size: 14px;

    .kf-item {
      font-weight: bold;
      color: #FFA01D;
    }
  }
  .qh-item_top{
    border-bottom: 1px dashed #d0cfcf;
    text-align: left;
    padding-top: 10px;
    padding-bottom: 10px;
    .qi-title{
      float: right;
      font-weight: bold;
      color: #f69d1c;
    }
  }
  .qh-item_top1{
    color: black;
    text-align: left;
    border-bottom:0
  }
  .el-dialog__header{
    text-align: left;
  }
}
</style>
